//
//  WaterFallFlowLayout.m
//  WaterfallFlow
//
//  Created by 方正刚 on 2017/8/21.
//  Copyright © 2017年 方正刚. All rights reserved.
//

#import "WaterFallFlowLayout.h"
#import "WaterFallFlowModel.h"

@interface WaterFallFlowLayout ()


@property (nonatomic, strong) NSMutableArray *attributeInfos;


/**
 contentSize的最大高度
 */
@property (nonatomic, assign) CGFloat maxH;

@end



@implementation WaterFallFlowLayout



- (NSMutableArray *)attributeInfos {
    if (_attributeInfos == nil) {
        _attributeInfos = [NSMutableArray arrayWithCapacity:4];
    }
    return _attributeInfos;
}



/**
 布局之前的准备工作
 */
- (void)prepareLayout {
    
    self.minimumLineSpacing = 10;
    self.minimumLineSpacing = 10;
    self.sectionInset = UIEdgeInsetsMake(20, 10, 0, 10);
    
    //计算Item宽度
    //不包含内边距的宽度
    CGFloat contentW = self.collectionView.bounds.size.width - self.sectionInset.left - self.sectionInset.right;
    CGFloat itemW = (contentW - (self.columns - 1) * self.minimumLineSpacing) / self.columns;
    
    NSMutableArray *columsY = [NSMutableArray array];
    
    for (int i = 0; i < self.columns; i++) {
        
        [columsY addObject:@(self.sectionInset.top)];
    }
    
    
    [self.dataList enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
       
        WaterFallFlowModel *flowModel = (WaterFallFlowModel *)self.dataList[idx];
        
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:idx inSection:0];
        
        UICollectionViewLayoutAttributes *attributes = [UICollectionViewLayoutAttributes layoutAttributesForCellWithIndexPath:indexPath];
        
        //计算Item高度
        CGFloat itemH = flowModel.h / flowModel.w * itemW;
        
        CGFloat itemX = 0.0;
        CGFloat itemY = 0.0;
        
        // 计算第几列
        int colmIndex = idx % self.columns;
        
        //计算x
        itemX = colmIndex * (itemW + self.minimumLineSpacing) + self.sectionInset.left;
      
        //计算y
        itemY = [columsY[colmIndex] floatValue];
        
        [columsY replaceObjectAtIndex:colmIndex withObject:@(itemY + itemH + self.minimumLineSpacing)];
        
        
        attributes.frame = CGRectMake(itemX, itemY, itemW, itemH);
        
        [self.attributeInfos addObject:attributes];
        
    }];
    
    
    self.maxH = [[columsY valueForKeyPath:@"@max.floatValue"] floatValue];
}



- (NSArray<UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    return self.attributeInfos;
}

- (CGSize)collectionViewContentSize {
    return CGSizeMake(self.collectionView.bounds.size.width, self.maxH);
}

@end
